package com.tczs.server;

import com.alibaba.fastjson.JSONObject;
import com.tczs.dispatch.CustomerException;
import com.tczs.server.request.ServerRequestModel;
import com.tczs.server.response.Response;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.apache.log4j.Logger;

@Sharable
public class HttpExecuteHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private static Logger logger = Logger.getLogger(HttpExecuteHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        FullHttpResponse fullHttpResponse = null;
        ServerRequestModel request = null;
        try {
             request = Config.getServerBuildRequest().buildRequest(msg);
            if("OPTIONS".equals(request.getMethod())){
                fullHttpResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
                fullHttpResponse.headers().set("Access-Control-Allow-Origin", "*");
                fullHttpResponse.headers().set("Access-Control-Allow-Headers", "*");
                fullHttpResponse.headers().set("Access-Control-Allow-Methods", "*");
            }else {
                fullHttpResponse = Config.getServerExecute().execute(request);
            }
        }catch (CustomerException e) {
            logger.error("friendly tips",e);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",555);
            jsonObject.put("errorMessage",e.getMessage());
            fullHttpResponse = Response.okResponse(jsonObject.toJSONString());
        }catch (Exception e){
            logger.error("server is error",e);
            fullHttpResponse = Response.errorResponse();
        }
        ChannelFuture future = ctx.channel().writeAndFlush(fullHttpResponse);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                ctx.channel().close();
            }
        });
    }

//    private FullHttpResponse execute(FullHttpRequest msg) {
//        ResponseResult result = null;
//        try {
//            ServerRequestModel request = Config.getServerBuildRequest().buildRequest(msg);
//            logger.info(request.toString());
//            checkIpBlack(request.getRemoteHost());
//            if(request.getUrl().startsWith("/html")) {
//                return Response.okStaticFileResponse("."+request.getUrl());
//            }
//            result = DispatchRequest.dispatch(request);
//        }catch (Exception e){
//            logger.error("build or dispatch request error",e);
//            return Response.errorResponse();
//        }
//        return MappingResponse.mappingHttpResponse(result);
//    }
//

}

